/* eslint-disable no-nested-ternary */
import React, { useState, useMemo, useCallback } from 'react';
import {
  Radio,
  Form,
  Field,
  Input,
  Grid,
  Balloon,
  NumberPicker,
  Button,
  Message,
} from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import CopyToClipboard from 'react-copy-to-clipboard';
import docs from 'utils/docs';
import './index.scss';

const radioItem = [
  {
    id: 'gitlab',
    value: '导入 Gitlab 代码库',
  },
  {
    id: 'other',
    value: '导入其他平台代码库',
  },
];

const protocolItem = [
  {
    id: 'HTTP',
    value: 'HTTP',
  },
  {
    id: 'SSH',
    value: 'SSH',
  },
];

const scopeItem = [
  {
    id: 'MEMBERCODE',
    value: '仅查询属于成员的代码库',
  },
  {
    id: 'ALLCODE',
    value: '查询可读权限的全部代码库',
  },
];

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
};
// const { Tooltip } = Balloon;

const ImportLocally = () => {
  const [radioValue, setRadioValue] = useState('gitlab');
  const useRadioItem = useMemo(() => {
    return radioItem.map((va) => {
      return <Radio value={va.id}>{va.value}</Radio>;
    });
  }, []);
  const radioChange = (value) => {
    setRadioValue(value);
  };

  const protocolRadioItem = useMemo(() => {
    return protocolItem.map((va) => {
      return (
        <Radio key={va.id} value={va.id}>
          {va.value}
        </Radio>
      );
    });
  }, []);
  const scopeRadioItem = useMemo(() => {
    return scopeItem.map((va) => {
      return (
        <Radio key={va.id} value={va.id}>
          {va.value}
        </Radio>
      );
    });
  }, []);
  const tokenLaber = useMemo(() => {
    return <span>个人访问令牌</span>;
  }, []);
  const accessTokenLaber = useMemo(() => {
    return (
      <span>
        Access Token
        <Balloon
          type="normal"
          align="t"
          closable={false}
          pure
          trigger={<YunxiaoIcon type="question-line" style={{ marginLeft: 2, color: '#1b9aee' }} />}
        >
          <span>
            Access Token 生成，请参考
            <a target="_blank" href={docs('import_locally_token')} rel="noreferrer">
              帮助文档
            </a>
          </span>
        </Balloon>
      </span>
    );
  }, []);

  const FormTwoRender = () => {
    const [commandTwo, setCommandTwo] = useState('');
    const field = Field.useField();
    const { init, validate, getValue } = field;
    return (
      <section className="Locally_form_two">
        <Form {...formItemLayout} field={field} labelAlign="top">
          <Grid.Row gutter={20}>
            <Grid.Col span={12}>
              <FormItem label="Host URL" required labelAlign="left" labelTextAlign="left">
                <Input
                  placeholder="如 https://self-managed-gitlab.com"
                  {...init('HostsURL', {
                    rules: [
                      {
                        required: true,
                        message: '该项为必填项',
                      },
                    ],
                  })}
                />
              </FormItem>
            </Grid.Col>
            <Grid.Col span={12}>
              <FormItem label={accessTokenLaber} required labelAlign="left" labelTextAlign="left">
                <Input
                  placeholder="如 67sf7648hnp"
                  {...init('AccessToken', {
                    rules: [
                      {
                        required: true,
                        message: '该项为必填项',
                      },
                    ],
                  })}
                />
              </FormItem>
            </Grid.Col>
          </Grid.Row>
          <FormItem
            label="生成库克隆地址协议"
            labelCol={{ span: 8 }}
            required
            labelAlign="left"
            labelTextAlign="left"
          >
            <Radio.Group
              {...init('protocolRadio', {
                initValue: 'HTTP',
                rules: [
                  {
                    required: true,
                    message: '该项为必填项',
                  },
                ],
              })}
            >
              {protocolRadioItem}
            </Radio.Group>
          </FormItem>
          {getValue('protocolRadio') === 'SSH' && (
            <FormItem label="SSH协议端口号" required labelAlign="left" labelTextAlign="left">
              <NumberPicker
                // placeholder="22"
                {...init('ssHport', {
                  initValue: '22',
                  rules: [
                    {
                      required: true,
                      message: '该项为必填项',
                    },
                    {
                      format: 'number',
                      message: '只能输入数字',
                    },
                  ],
                })}
              />
            </FormItem>
          )}
          <FormItem label="期望导入的库范围" required>
            <Radio.Group
              {...init('scopeRadio', {
                initValue: 'MEMBERCODE',
                rules: [
                  {
                    required: true,
                    message: '该项为必填项',
                  },
                ],
              })}
            >
              {scopeRadioItem}
            </Radio.Group>
          </FormItem>
          <Button
            type="primary"
            onClick={() => {
              validate((error, value) => {
                const flag = value.protocolRadio === 'HTTP' ? true : value.ssHport;
                const sshString = `--ssh_port=${value.ssHport}`;
                if (error) {
                  return false;
                } else if (
                  value.HostsURL &&
                  value.AccessToken &&
                  value.protocolRadio &&
                  value.scopeRadio &&
                  flag
                ) {
                  const comValue = `codeup repo generate --platform=gitlab --host=${
                    value.HostsURL
                  } --access_token=${value.AccessToken} --protocol=${
                    value.protocolRadio
                  } --membership=${value.scopeRadio === 'ALLCODE'} ${
                    value.protocolRadio === 'HTTP' ? '' : sshString
                  }`;
                  return new Promise((resolve) => {
                    setTimeout(() => resolve(setCommandTwo(comValue)), 0);
                  });
                }
              });
            }}
          >
            生成命令
          </Button>
          {commandTwo && (
            <>
              <section className="command_display_two">
                <article className="command_display_content">{commandTwo}</article>
                <div className="command_display_hover">
                  {commandTwo && (
                    <CopyToClipboard
                      text={commandTwo}
                      onCopy={() =>
                        Message.success({
                          title: '复制成功',
                        })
                      }
                    >
                      <YunxiaoIcon type="copy-line" style={{ color: '#1b9aee' }} />
                    </CopyToClipboard>
                  )}
                </div>
              </section>
              <section className="command_display_content_right">* 请粘贴命令到本地执行</section>
            </>
          )}
        </Form>
      </section>
    );
  };
  const FormTherrRender = () => {
    const [commandTherr, setCommandTherr] = useState('');
    const field = Field.useField();
    const { init, validate } = field;
    return (
      <section className="Locally_form_three">
        <Form {...formItemLayout} field={field} labelAlign="top">
          <FormItem
            label={
              <>
                <span>请输入配置文件路径</span>
                <span style={{ position: 'absolute', right: '-480px' }}>
                  <a target="_blank" href={docs('import_locally_personal_token')} rel="noreferrer">
                    如何获取以下参数？
                  </a>
                </span>
              </>
            }
            required
          >
            <Input
              placeholder="请输入配置文件"
              {...init('path', {
                rules: [
                  {
                    required: true,
                    message: '该项为必填项',
                  },
                  {
                    validator: '',
                  },
                ],
              })}
            />
          </FormItem>
          <Grid.Row gutter={20}>
            <Grid.Col span={12}>
              <FormItem label="阿里云AK" required labelAlign="left" labelTextAlign="left">
                <Input
                  placeholder="请输入阿里云AK"
                  {...init('aliyunAK', {
                    rules: [
                      {
                        required: true,
                        message: '该项为必填项',
                      },
                      {
                        validator: '',
                      },
                    ],
                  })}
                />
              </FormItem>
            </Grid.Col>
            <Grid.Col span={12}>
              <FormItem label="阿里云SK" required labelAlign="left" labelTextAlign="left">
                <Input
                  placeholder="请输入阿里云SK"
                  {...init('aliyunSK', {
                    rules: [
                      {
                        required: true,
                        message: '该项为必填项',
                      },
                      {
                        validator: '',
                      },
                    ],
                  })}
                />
              </FormItem>
            </Grid.Col>
          </Grid.Row>
          <FormItem label={tokenLaber} required>
            <Input
              placeholder="请输入个人访问令牌"
              {...init('token', {
                rules: [
                  {
                    required: true,
                    message: '该项为必填项',
                  },
                  {
                    validator: '',
                  },
                ],
              })}
            />
          </FormItem>
          <Button
            type="primary"
            onClick={() => {
              validate((error, value) => {
                const tokenValue = value.token ? `--personal_access_token=${value.token}` : '';
                if (error) {
                  return false;
                } else if (value.path && value.aliyunAK && value.aliyunSK) {
                  const comValue = `codeup repo import --repo_list_path=${value.path} --organization=${window.FORCE.organization.organization_id} --access_key=${value.aliyunAK} --secret_key=${value.aliyunSK} ${tokenValue}`;
                  setCommandTherr(comValue);
                }
              });
            }}
          >
            生成命令
          </Button>
          {commandTherr && (
            <>
              <section className="command_display_therr">
                <article className="command_display_content">{commandTherr}</article>
                <div className="command_display_hover">
                  {commandTherr && (
                    <CopyToClipboard
                      text={commandTherr}
                      onCopy={() =>
                        Message.success({
                          title: '复制成功',
                        })
                      }
                    >
                      <YunxiaoIcon type="copy-line" style={{ color: '#1b9aee' }} />
                    </CopyToClipboard>
                  )}
                </div>
              </section>
              <section className="command_display_content_right">* 请粘贴命令到本地执行</section>
            </>
          )}
        </Form>
      </section>
    );
  };
  const LocallyForm = useCallback(() => {
    return (
      <React.Fragment>
        <section className="form_two_down">
          <FormTwoRender />
        </section>
      </React.Fragment>
    );
  }, []);
  const formtherrhander = useCallback(() => {
    return (
      <React.Fragment>
        <FormTherrRender />
      </React.Fragment>
    );
  }, []);
  return (
    <React.Fragment>
      <section className="Locally_desc">
        <section>三步完成代码库批量迁移</section>
        <a href={docs('import_locally_tool_download')} target="_blank" rel="noreferrer">
          查看完整帮助
        </a>
      </section>
      <section className="Locally_ont_title">
        <section>1. 下载迁移工具</section>
        <a href={docs('import_locally_tool_download_href')} target="_blank" rel="noreferrer">
          前往下载
        </a>
      </section>
      {radioValue === 'other' ? (
        <React.Fragment>
          <section className="Locally_checkout">
            <section className="Locally_checkout_title">2. 创建导入配置文件</section>
            <a target="_blank" href={docs('import_locally_file_writing')} rel="noreferrer">
              查看配置文件编写格式
            </a>
          </section>
          <>
            <section className="locally_ridio_group">
              <Radio.Group value={radioValue} onChange={radioChange}>
                {useRadioItem}
              </Radio.Group>
            </section>
            <section className="locally_other">
              手动在当前目录下创建一个导入配置文件，根据配置文件格式自行填入期望导入的库地址列表，任意有权限的代码库均可。
              <section style={{ paddingTop: 6 }}>
                <a target="_blank" href={docs('import_locally_file_writing')} rel="noreferrer">
                  查看配置文件编写格式
                </a>
              </section>
            </section>
          </>
        </React.Fragment>
      ) : radioValue === 'gitlab' ? (
        <React.Fragment>
          <section className="Locally_checkout">
            <section className="Locally_checkout_title">2. 创建导入配置文件</section>
            <a target="_blank" href={docs('import_locally_file_writing')} rel="noreferrer">
              查看配置文件编写格式
            </a>
          </section>
          <section className="locally_ridio_group">
            <Radio.Group value={radioValue} onChange={radioChange}>
              {useRadioItem}
            </Radio.Group>
          </section>
          {LocallyForm()}
        </React.Fragment>
      ) : null}
      {radioValue === 'other' ? (
        <React.Fragment>
          <div className="form_three_down">3. 生成导入命令</div>
          {formtherrhander()}
        </React.Fragment>
      ) : (
        <React.Fragment>
          <div className="form_three_down">3. 生成导入命令</div>
          {formtherrhander()}
        </React.Fragment>
      )}
    </React.Fragment>
  );
};

export default ImportLocally;
